package de.guidoludwig.jtm.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

public class LogHandler extends Handler {
	
	private List<LogRecord> messages = new ArrayList<LogRecord>();
	boolean isClosed = false;

	@Override
	public void publish(LogRecord record) {
		if (!isClosed) {
			messages.add(record);
		}
	}

	@Override
	public void flush() {
		messages.clear();
	}

	@Override
	public void close() throws SecurityException {
		flush();
		isClosed =  true;
	}
	
	protected List<String> getMessages() {
		List<String> formatted = new ArrayList<String>();
		for (LogRecord record : messages) {
			formatted.add(format(record));
		}
		return formatted;
	}
	
	private String format(LogRecord log) {
		return new Date(log.getMillis()) + " " + log.getLevel().getName() + " " + log.getMessage();
	}
	
}

